﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.IO;
using System.Data.OleDb;
using System.Globalization;
using System.Xml;
using System.Collections.Specialized;

namespace OriBruniClock
{
    public partial class frm_main : Form
    {
        public frm_main()
        {
            InitializeComponent();
        }

        private void frm_main_Load(object sender, EventArgs e)
        {
            foreach (string portname in SerialPort.GetPortNames())
            {
                cmbCOMPort.Items.Add(portname);
            }
            // Avvio i semafori colorati
            semaforo_verde.Visible = false;
            semaforo_rosso.Visible = true;
            OutputWindow.Text = "Avvio";
            cmbCOMPort.Text = ConfigurationManager.AppSettings["COMPort"];
            cb_baudrate.Text = ConfigurationManager.AppSettings["BaudRate"];
        }

        private void frm_main_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (comport.IsOpen)
                comport.Close();
            semaforo_verde.Visible = false;
            semaforo_rosso.Visible = true;
        }

        private void OpenPort_Click(object sender, EventArgs e)
        {
            comport.PortName = cmbCOMPort.Text;
            bool error = false;

            // If the port is open, close it.
            if (comport.IsOpen) comport.Close();
            else
            {
                // Set the port's settings
                //comport.BaudRate = int.Parse(cmbBaudRate.Text);
                comport.BaudRate = Convert.ToInt32(cb_baudrate.Text);
                comport.DataBits = 8;
                comport.DtrEnable = false;
                comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "One");
                comport.Parity = (Parity)Enum.Parse(typeof(Parity), "None");

                try
                {
                    // Open the port
                    comport.Open();
                }
                catch (UnauthorizedAccessException) { error = true; }
                catch (IOException) { error = true; }
                catch (ArgumentException) { error = true; }

                if (error) MessageBox.Show(this, "Could not open the COM port.  Most likely it is already in use, has been removed, or is unavailable.", "COM Port Unavalible", MessageBoxButtons.OK, MessageBoxIcon.Stop);

            }
            OutputWindow.Text = "Aperta\n";
            semaforo_verde.Visible = true;
            semaforo_rosso.Visible = false;
        }

        private void cmbCOMPort_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.AppSettings.Settings["COMPort"].Value = cmbCOMPort.Text;
            config.Save(ConfigurationSaveMode.Modified);
        }

        private void btn_start_timesincro_Click(object sender, EventArgs e)
        {
            System.DateTime moment;
            moment = DateTime.Now;
            do {
                OutputWindow.AppendText("Entrata:" + moment.Millisecond.ToString() + '\n');
                Thread.Sleep(1000 - moment.Millisecond);
                moment = DateTime.Now;

            } while (moment.Millisecond == 0);
            String str1 = DateTime.Now.ToString("H:m:s");
            comport.WriteLine("UpdRTCTime:" + str1 + ':' + '\n'); 
            OutputWindow.AppendText("Uscita:" + moment.Millisecond.ToString() + '\n');
            OutputWindow.AppendText("UpdRTCTime:" + str1 + ':' + '\n');
        }

        private void comport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            OutputWindow.AppendText(comport.ReadExisting().ToString());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string HH = cb_h.Text;
            string MM = cb_m.Text;
            string SS = cb_s.Text;
            if ((HH != null) && (MM != null) && (SS != null))
            {
                String str1 = HH + ":" + MM + ":" + SS;
                OutputWindow.AppendText("UpdOPP:" + str1 + ":" + '\n');
                comport.WriteLine("UpdOPP:" + str1 + ":" + '\n'); 
            }
        }

        private void btn_cancella_Click(object sender, EventArgs e)
        {
            OutputWindow.Clear();
        }

        private void cb_baudrate_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.AppSettings.Settings["BaudRate"].Value = cb_baudrate.Text;
            config.Save(ConfigurationSaveMode.Modified);
        }
    }
}
